var util = require('../../libs/util.js'); 
var pathtool = require('../../libs/pathtool.js');
var moment = require('../../libs/moment.min.js');
moment.locale('zh-cn');
var app = getApp();
Page({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    currentVehicleType: "1",
    vehicleType: { "0": 'minibusM', "1": '4.2', "2": '5.2', "3": '6.8', "4": '7.6' },
    isReturn: false,
    name: "",
    pathData: [{ name: '按此输入发货点', type: 'warehouse',address:'', hasAddress: false }, { name: '按此输入收货点', type: 'shop',address:'', hasAddress: false }],
    distance: 0,
    duration: 0,
    restriction: false,
    driver_name: "",
    vehicle_plate: "点击安排送货车辆",
    postData: {
      delivery_date: moment().format('YYYY-MM-DD'),
      loading_time: '00:00',
      vehicle: null,
      driver: null,
      warehouse: '',
      distance: '',
      duration: '',
      carrier: '',
      customer: ''
    },
    delivery_date: moment().format('YYYY-MM-DD'),
    loading_time: '00:00',
    isAdmin:true
  },
  onShareAppMessage: function () {
    return {
      title: app.appName,
      path: '/pages/index/index'
    }
  },
  onLoad: function (e) {
    wx.setNavigationBarTitle({ "title": app.appName +"--新增常用路线" });
    this.setData({
      mode:e.mode,
      id:e.id,
      name:e.name||'',
      isAdmin: (app.globalData.admin ? true : false)
    });
    if(e.id){
      this.loadData(e.id);
    }
  },
  loadData(id) {
    wx.showLoading({
      title: '加载数据中...',
    });
    var that = this;
    if(id){
      util.getData("usuallyPathList2", { path_id: id }, function (res, error) {
        console.log(res)
        if (res.data.success) {
          console.log(res.data.data)
          var _data = res.data.data[0], _pathData = [];
          for (var i = 0; i < _data.length; i++) {
            var coord = String(_data[i].coord).split(",");
            if (_data[i].type == 'warehouse') {
              _pathData.push({ id: _data[i].ID, name: _data[i].name, type: _data[i].type, address: _data[i].address, loading_time: _data[i].loading_time, latitude: coord[0], longitude: coord[1], hasAddress: true });
            } else  {
              _pathData.push({ id: _data[i].ID, name: _data[i].name, type: _data[i].type, address: _data[i].address, shop_time: _data[i].shop_time, latitude: coord[0], longitude: coord[1], hasAddress: true });
            }
          };
          that.setData({
            pathData: _pathData
          });
          pathtool.calculateDistance(that, that.data.isReturn, that.data.pathData, false);
          if(res.data.data[1] && res.data.data[1][0]){
            console.log(res.data.data[1][0])
            that.setData({
              pathName :that.formatVaule(res.data.data[1][0].name),
              driver:that.formatVaule(res.data.data[1][0].driver),
              plate:that.formatVaule(res.data.data[1][0].plate),
              driver_name: that.formatVaule(res.data.data[1][0].driver_name),
              vehicle_plate: that.formatVaule(res.data.data[1][0].plate),
              vehicle:that.formatVaule(res.data.data[1][0].vehicle),
              loading_time:that.formatVaule(res.data.data[1][0].loading_time),
              price : that.formatVaule(res.data.data[1][0].price),
              onePrice : that.formatVaule(res.data.data[1][0].onePrice) || 0,
              total_price : that.formatVaule(res.data.data[1][0].total_price) || 0,
              customer : that.formatVaule(res.data.data[1][0].customer),
              customerName : that.formatVaule(res.data.data[1][0].customerName),
              isReturn : res.data.data[1][0].isReturn == '1' ? true : false
            })
          }
          wx.hideLoading()
        }
      });
    }
    
  },
  formatVaule:function(val){
     if(!val || val == 'null' || val == 'undefined'){
      return ''
     }else{
       return val
     }
  },
  onShow: function () {
    var that = this;
    wx.getStorage({
      key: 'path_vehicle',
      success: function (res) {
        if (res.data) {
          that.setData({
            driver_name: res.data.name,
            vehicle_plate: res.data.plate
          });
          var postData = that.data.postData;
          postData.driver_name = res.data.name
          postData.vehicle = res.data.ID;
          postData.driver = res.data.driver;
          postData.plate = res.data.plate;
          that.setData({
            postData: postData
          });
          wx.removeStorage({
            key: 'path_vehicle',
            success: function (res) {
            }
          });
        }
      }
    });
    wx.getStorage({
      key: 'path_warehouse',
      success: function (res) {
        if (res.data) {
          var data = that.data.pathData;
          var loading_time = res.data.loading_time;
          var timepatt = new RegExp("^[0-9]{2}:[0-9]{2}");
          if (!timepatt.test(loading_time)) {
            loading_time = '00:00';
          };
          data[res.data.index] = { name: res.data.name, type: 'warehouse', address: res.data.address, latitude: res.data.latitude, longitude: res.data.longitude, loading_time: loading_time, id: res.data.value, hasAddress: true };
          that.setData({
            pathData: data
          });
          var postData = that.data.postData;
          postData.warehouse = res.data.value; 
          postData.loading_time = loading_time; 

          var pathName = [];
          for (var i = 0; i < data.length; i++) {
            pathName.push(data[i].name);
          }

          that.setData({
            postData: postData,
            pathName: pathName.join("-")
          });

          pathtool.calculateDistance(that, that.data.isReturn, that.data.pathData, false);
          wx.removeStorage({
            key: 'path_warehouse',
            success: function (res) {
            }
          });
        }
      }
    });
    wx.getStorage({
      key: 'path_shop',
      success: function (res) {
        if (res.data) {
          var data = that.data.pathData;
          var receive_time = res.data.receive_time;
          var timepatt = new RegExp("^[0-9]{2}:[0-9]{2}");
          if (!timepatt.test(receive_time)) {
            receive_time = '00:00';
          };
          data[res.data.index] = { name: res.data.name, type: 'shop', address: res.data.address, latitude: res.data.latitude, longitude: res.data.longitude, receive_time: receive_time, id: res.data.value, hasAddress: true };
          var pathName = [];
          for (var i = 0; i < data.length; i++) {
            pathName.push(data[i].name);
          }

          that.setData({
            pathData: data,
            pathName: pathName.join("-")
          });
          pathtool.calculateDistance(that, that.data.isReturn, that.data.pathData, false);
          wx.removeStorage({
            key: 'path_shop',
            success: function (res) {
            }
          });
        }
      }
    }); 
    wx.getStorage({
      key: 'path_historyAddress',
      success: function (res) {
        if (res.data) {
          var data = that.data.pathData;
          data[res.data.index].name = res.data.name;
          data[res.data.index].address = res.data.address;
          data[res.data.index].latitude = res.data.latitude;
          data[res.data.index].longitude = res.data.longitude;
          data[res.data.index].province = res.data.province;
          data[res.data.index].city = res.data.city;
          data[res.data.index].area = res.data.area;
          data[res.data.index].hasAddress = true;
          that.setData({
            pathData: data
          });
          pathtool.calculateDistance(that,  that.data.isReturn, that.data.pathData, false);
          wx.removeStorage({
            key: 'path_historyAddress',
            success: function (res) {
            }
          });
        }
      }
    });
    wx.getStorage({
      key: 'warehouseConfig',
      success: function (res) {
        if (res.data) {
          var data = that.data.pathData,postData = that.data.postData, index = res.data.index;
          if (res.data.alias){
            data[index].name = res.data.alias;
          }
          data[index].delivery_date = res.data.delivery_date;
          data[index].loading_time = res.data.loading_time;
          data[index].depart_time = res.data.depart_time;
          data[index].shipper = res.data.shipper;
          data[index].shipper_phone = res.data.shipper_phone;
          postData.delivery_date = res.data.delivery_date;
          postData.loading_time = res.data.loading_time;
          that.setData({
            pathData: data,
            postData: postData
          });
          wx.removeStorage({
            key: 'warehouseConfig',
            success: function (res) {
            }
          });
        }
      }
    });
    wx.getStorage({
      key: 'shopConfig',
      success: function (res) {
        if (res.data) {
          var data = that.data.pathData, index = res.data.index;
          if (res.data.alias) {
            data[index].name = res.data.alias;
          }
          data[index].receive_time = res.data.receive_time;
          data[index].receiver = res.data.receiver;
          data[index].receiver_phone = res.data.receiver_phone;
          that.setData({
            pathData: data
          });
          wx.removeStorage({
            key: 'shopConfig',
            success: function (res) {
            }
          });
        }
      }
    });
    wx.getStorage({
      key: 'path_usually',
      success: function (res) {
        if (res.data) {
          console.log(res.data)
          var postData = {
            delivery_date: util.dateObjectformat(new Date(), 'yyyy-MM-dd'),
            loading_time: res.data.loading_time,
            depart_time: res.data.depart_time,
            vehicle: res.data.vehicle,
            driver: res.data.driverId,
            warehouse: res.data.warehouse,
            price: res.data.price,
            distance: res.data.mile,
            duration: res.data.duration
          };
          that.setData({
            postData: postData,
            price: res.data.price || 0,
            distance: res.data.mile || 0,
            duration: res.data.duration || 0,
            driver_name: '司机：' + res.data.driver,
            vehicle_plate: '车辆：' + res.data.plate,
            pathName: res.data.name
          });
          util.getData("usuallyPathList", { path_id: res.data.ID }, function (res, error) {
            if (res.data.success) {
              console.log(res.data.data)
              var _data = res.data.data, _pathData = [];
              for (var i = 0; i < _data[0].length; i++) {
                var coord = String(_data[0][i].coord).split(",");
                _pathData.push({ id: _data[0][i].ID, name: _data[0][i].name, type: 'warehouse', address: _data[0].address, latitude: coord[0], longitude: coord[1], hasAddress: true });
              };
              for (var i = 0; i < _data[1].length; i++) {
                var coord = String(_data[1][i].coord).split(",");
                _pathData.push({ id: _data[1][i].ID, name: _data[1][i].name, type: 'shop', address: _data[1][i].address, latitude: coord[0], longitude: coord[1], hasAddress: true });
              };
              that.setData({
                pathData: _pathData
              });
            }
          });
          wx.removeStorage({
            key: 'path_usually',
            success: function (res) {
            }
          });
        }
      }
    });
    wx.getStorage({
      key: 'path_map',
      success: function (res) {
        if (res.data) {
          that.setData({
            pathData: res.data
          });
          wx.removeStorage({
            key: 'path_map',
            success: function (res) {
            }
          });
        }
      }
    });
    wx.getStorage({
      key: 'path_customer',
      success: function (res) {
        if (res.data) {
          that.setData({
            customerName: res.data.name
          });
          var postData = that.data.postData;
          postData.customer = res.data.value;
          postData.customerName = res.data.name;
          that.setData({
            postData: postData
          });
          wx.removeStorage({
            key: 'path_customer',
            success: function (res) {
            }
          });
        }
      }
    });
  },
  onReady: function () {
    wx.hideToast();
  }, 
  bindInput: function (e) {
    var item = String(e.currentTarget.id), item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);

    if (item == 'delivery_date') {
      this.setData({
        'postData.delivery_date': e.detail.value
      })
    }
    if (item == 'loading_time') {
      this.setData({
        'postData.loading_time': e.detail.value
      })
    }
  }, 
  swithchChange: function (e) {
    var item = String(e.currentTarget.id), item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);
  }, 
  selectVehicle: function () {
    wx.navigateTo({
      url: '/pages/index/pathSelectVehicle'
    })
  },
  selectAddress: function (e) {
    var that = this;
    var index = String(e.currentTarget.id).replace("path", "");
    //console.log(e);
    wx.chooseLocation({
      success: function (res) {
        //console.log(res)
        var address = res.address;
        var latitude = res.latitude;
        var longitude = res.longitude;
        var name = res.name;

        util.getData("/xypapi/map/routerCalculate/geocode", {
          latitude: res.latitude,
          longitude: res.longitude
        }, function (geo, error) {
          console.log(geo); console.log(error)
          if (geo.data.success) {
            that.setData({
              "addressComponent.province": geo.data.component.province,
              "addressComponent.city": geo.data.component.city,
              "addressComponent.area": geo.data.component.district
            });
          }
          var pathData = that.data.pathData, _pathData = [], pathName = [];
          for (var i = 0; i < pathData.length; i++) {
            var n = pathData[i], _name = name || address;
            if (i == index && _name) {
              n.name = _name;
              n.address = address;
              n.latitude = latitude;
              n.longitude = longitude;
              n.province = geo.data.component.province;
              n.city = geo.data.component.city;
              n.area = geo.data.component.district;
              n.hasAddress = true;
            };
            pathName.push(n.name)
            _pathData.push(n);
          }
          that.setData({
            pathData: _pathData,
            pathName: pathName.join("-")
          });

          wx.getStorage({
            key: 'historyAddress',
            complete: function (res) {//console.log(res)
              var data = res.data, _data = [];
              if (res.errMsg == 'getStorage:ok') {
                _data.push({ name: name, address: address, latitude: latitude, longitude: longitude, province: geo.data.component.province, city: geo.data.component.city, area: geo.data.component.district });
                for (var i = 0; i < data.length; i++) {
                  if (i < 9) {
                    _data.push(data[i])
                  }
                }
              } else {
                _data.push({ name: name, address: address, latitude: latitude, longitude: longitude, province: geo.data.component.province, city: geo.data.component.city, area: geo.data.component.district });
              };
              wx.setStorage({
                key: "historyAddress",
                data: _data
              });
            }
          });

          pathtool.calculateDistance(that, that.data.isReturn, that.data.pathData, false);
        });

      }
    })
  },
  addAddress: function (e) {
    var that = this;
    console.log(e);
    var index = String(e.currentTarget.id).replace("path", "");
    var type = e.currentTarget.dataset.pos;
    var pathData = that.data.pathData;

    if (type == "warehouse") {
      wx.showActionSheet({
        itemList: ['增加一个发货点', '删除本发货点', '历史地址记录', '选择已注册发货点', '设置更多发货信息'],
        success: function (e) {
          //增加一个发货点
          if (e.tapIndex == 0) {
            // wx.showToast({
            //   title: "仅限1个发货点",
            //   image: '/images/wrong.png',
            //   duration: 2000
            // });
            var _pathData = [];
            for (var i = 0; i < pathData.length; i++) {
              var n = pathData[i];
              _pathData.push(n);
              if (i == index) {
                if (type == "warehouse") {
                  _pathData.push({ name: '按此输入发货点', type: 'warehouse', address: '', hasAddress: false });
                }
              };
            }
            that.setData({
              pathData: _pathData
            });
            //删除本发货点
          } else if (e.tapIndex == 1) {
            var  _pathData = [], warehouseNumber = 0;
            //检索是否只有一个发货点
            for (var i = 0; i < pathData.length; i++) {
              if (pathData[i].type == 'warehouse') {
                warehouseNumber++;
              };
            }
            if (warehouseNumber == 1) {
              wx.showToast({
                title: "须留1个发货点",
                image: '/images/wrong.png',
                duration: 2000
              });
              return false;
            }
            //找出并删除
            var pathName = [];
            for (var i = 0; i < pathData.length; i++) {
              var n = pathData[i];
              if (i != index) {
                _pathData.push(n);
                pathName.push(n.name);
              };
            }
            that.setData({
              pathData: _pathData,
              pathName: pathName.join("-")
            });
            pathtool.calculateDistance(that,  that.data.isReturn, that.data.pathData, false);
            //历史地址记录
          } else if (e.tapIndex == 2) {
            wx.navigateTo({
              url: '/pages/index/historyAddress?index=' + index
            })
            //选择已注册发货点
          } else if (e.tapIndex == 3) {
            wx.navigateTo({
              url: '/pages/index/warehouseList?index=' + index
            })
          } else if (e.tapIndex == 4) {
            if (!pathData[index].hasAddress){
              wx.showToast({
                title: "请先规划路线",
                image: '/images/wrong.png',
                duration: 2000
              });
              return false;
            }
            wx.navigateTo({
              url: '/pages/index/warehouseConfig?index=' + index + '&delivery_date=' + pathData[index].delivery_date + '&loading_time=' + pathData[index].loading_time + '&depart_time=' + pathData[index].depart_time + '&shipper=' + pathData[index].shipper +'&shipper_phone=' + pathData[index].shipper_phone
            })
          }
        }
      })
      //_pathData.push({ name: '按此输入发货点', type: 'warehouse' });
    } else if (type == "shop") {
      wx.showActionSheet({
        itemList: ['增加一个收货点', '删除本收货点', '历史地址记录', '选择已注册收货点', '设置更多收货信息'],
        success: function (e) {
          //增加一个收货点
          if (e.tapIndex == 0) {
            var _pathData = [];
            for (var i = 0; i < pathData.length; i++) {
              var n = pathData[i];
              _pathData.push(n);
              if (i == index) {
                if (type == "shop") {
                  _pathData.push({ name: '按此输入收货点', type: 'shop', address: '', hasAddress: false });
                }
              };
            }
            that.setData({
              pathData: _pathData
            });
            //删除本收货点
          } else if (e.tapIndex == 1) {
            var _pathData = [], shopNumber = 0;
            //检索是否只有一个收货点
            for (var i = 0; i < pathData.length; i++) {
              if (pathData[i].type == 'shop') {
                shopNumber++;
              };
            }
            if (shopNumber == 1) {
              wx.showToast({
                title: "须留1个收货点",
                image: '/images/wrong.png',
                duration: 2000
              });
              return false;
            }
            //找出并删除
            var pathName = [];
            for (var i = 0; i < pathData.length; i++) {
              var n = pathData[i];
              if (i != index) {
                _pathData.push(n);
                pathName.push(n.name);
              };
            }
            that.setData({
              pathData: _pathData,
              pathName: pathName.join("-")
            });
            pathtool.calculateDistance(that, that.data.isReturn, that.data.pathData, false);
            //历史地址记录
          } else if (e.tapIndex == 2) {
            wx.navigateTo({
              url: '/pages/index/historyAddress?index=' + index
            })
            //选择已注册收货点
          } else if (e.tapIndex == 3) {
            wx.navigateTo({
              url: '/pages/index/shopList?index=' + index
            })
          } else if (e.tapIndex == 4) {
            if (!pathData[index].hasAddress) {
              wx.showToast({
                title: "请先规划路线",
                image: '/images/wrong.png',
                duration: 2000
              });
              return false;
            }
            wx.navigateTo({
              url: '/pages/index/shopConfig?index=' + index + '&receive_time=' + pathData[index].receive_time + '&receiver=' + pathData[index].receiver + '&receiver_phone=' + pathData[index].receiver_phone
            })
          }
        }
      })
      //_pathData.push({ name: '按此输入收货点', type: 'shop' });
    }
  },
  showMap: function () {
    if (this.data.distance == 0) {
      wx.showToast({
        title: "请先规划路线",
        image: '/images/wrong.png',
        duration: 2000
      });
      return false;
    };
    wx.setStorage({
      key: "path_map",
      data: this.data.pathData
    });
    wx.navigateTo({
      url: '/pages/index/map'
    })
  },
  selectCustomer: function() {
    wx.navigateTo({
      url: '/pages/index/customerList'
    })
  },
  changeVehicleType: function (e) {
    var that = this;
    that.setData({
      currentVehicleType: e.detail.current
    })
    pathtool.calculateDistance(that,  that.data.isReturn, that.data.pathData, false);
  },
  isReturn: function (e) {
    var that = this;
    that.setData({
      isReturn: !that.data.isReturn
    })
    if (that.data.distance > 0) {
      pathtool.calculateDistance(that, that.data.isReturn, that.data.pathData, false);
    }
  },
  saveNewPath: function () {
    var that = this;
    var postData = that.data.postData;
    // var _pathData = pathtool.checkPathPointList(that, that.data.pathData);//检查和修正路线途径点合法性
    // if (_pathData.errMsg) {
    //   wx.showToast({
    //     title: "请检查路线",
    //     image: '/images/wrong.png',
    //     duration: 3000
    //   });
    //   return false;
    // }

    //pathtool.calculateDistance(that, that.data.vehicleType[that.data.currentVehicleType], that.data.isReturn, that.data.pathData, true);

    var pathData = that.data.pathData;
    
    wx.showLoading({
      title: '校验数据中...',
      mask: true
    });
    //var errorText = "";
    // for (var j = 0;j < pathData.length;j++){
    //   if (!pathData[j].id){
    //     if (pathData[j].type == "warehouse" & !pathData[j].delivery_date){
    //       errorText += pathData[j].name + "的配送时间未填写；\n"
    //     }
    //     if (pathData[j].type == "shop" & !pathData[j].receive_time) {
    //       errorText += pathData[j].name + "的收货时间未填写；\n"
    //     }
    //   }
    // }
    if (postData.name == '') {
      wx.showToast({
        title: "请输入路线名",
        image: '/images/wrong.png',
        duration: 2000
      });
      return false;
    }
    if (postData.distance == '') {
      wx.showToast({
        title: "里程计算失败",
        image: '/images/wrong.png',
        duration: 2000
      });
      return false;
    }
    // if (postData.loading_time == '') {
    //   wx.showToast({
    //     title: "未配置发货时间",
    //     image: '/images/wrong.png',
    //     duration: 2000
    //   });
    //   return false;
    // }
    for (var i = 0; i < pathData.length;i++){
      pathData[i].sort = i+1;
    }
    postData.path = pathData;
    postData.name = that.data.pathName;
    postData.price = that.data.price||'';
    postData.onePrice = that.data.onePrice || 0;
    postData.total_price = that.data.total_price || 0;
    postData.isReturn = that.data.isReturn ? 1 : 0;
    postData.customer = that.data.customer||'';
    postData.customerName = that.data.customerName||'';
    postData.openid = app.globalData.openid;
    postData.CO_ID = app.globalData.CO_ID;
    postData.user_id = app.globalData.user_id;
    console.log(postData);
    wx.hideLoading();
    if(that.data.mode == 'edit' && that.data.id){
      postData.ID = that.data.id
      wx.showModal({
        title: '常用路线',
        content: '是否确认保存常用路线',
        success: function (res) {
          if (res.confirm) {
            wx.showLoading({
              title: '请稍候...',
            });
            util.putData("saveNewPath", {
              data: JSON.stringify(postData)
            }, function (res, error) {
              console.log(res); console.log(error)
              wx.hideLoading();
              if (error) {
                wx.showToast({
                  title: res.data.data,
                  image: '/images/wrong.png',
                  duration: 3000
                });
                return false;
              }
              if (res.data.success) {
                wx.showToast({
                  title: "保存成功",
                  icon: 'success',
                  success:function(){
                    setTimeout(function(){
                      wx.redirectTo({
                        url: '/pages/index/usuallyPath'
                      })
                    },3000);
                  }
                });
              }
            });
          } else if (res.cancel) {
          }
        }
      })
    }else{
      wx.showModal({
        title: '常用路线',
        content: '是否确认保存常用路线',
        success: function (res) {
          if (res.confirm) {
            wx.showLoading({
              title: '请稍候...',
            });
            util.postData("saveNewPath", {
              data: JSON.stringify(postData)
            }, function (res, error) {
              console.log(res); console.log(error)
              wx.hideLoading();
              if (error) {
                wx.showToast({
                  title: res.data.data,
                  image: '/images/wrong.png',
                  duration: 3000
                });
                return false;
              }
              if (res.data.success) {
                wx.showToast({
                  title: "保存成功",
                  icon: 'success',
                  success:function(){
                    setTimeout(function(){
                      wx.redirectTo({
                        url: '/pages/index/usuallyPath'
                      })
                    },3000);
                  }
                });
              }
            });
          } else if (res.cancel) {
          }
        }
      })
    }
    
    
  },
  cancelConfirmData: function () {
    wx.redirectTo({
      url: '/pages/index/usuallyPath'
    })
  }
});